#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;

const int PORT=8080;

int main()
{
    // 创建套接字
    int serverfd=socket(AF_INET,SOCK_STREAM,0); //IPv4 tcp

    // 绑定IP和port
    sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET; //设置IPv4
    server.sin_port=htons(PORT); //htons处理port htonl处理IP
    server.sin_addr.s_addr=INADDR_ANY; // 任意

    // 绑定
    if(bind(serverfd,(sockaddr*)&server,sizeof(server))<0)
    {
        cerr<<"bind errno"<<endl;
        close(serverfd);
        exit(-1);
    }

    if(listen(serverfd,SOMAXCONN)<0)
    {
        cerr<<"listen errno"<<endl;
        close(serverfd);
        exit(-1);
    }

    sockaddr_in client;
    socklen_t len=sizeof(client);
    memset(&client,0,sizeof(client));
    int clientfd=accept(serverfd,(sockaddr*)&client,&len);
    if(clientfd<0)
    {
        cerr<<"accept errno"<<endl;
        close(serverfd);
        exit(-1);
    }

    // 将客户端的二进制IP地址转换为可读字符串
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client.sin_addr, client_ip, INET_ADDRSTRLEN);
    cout << "客户端已连接: " << client_ip <<endl;


    char buffer[1024];
    memset(&buffer,0,sizeof(buffer));

    while(true)
    {
        int sz=recv(clientfd,buffer,sizeof(buffer),0);
        if(sz==0)
        {
            cout<<"客户端断开连接"<<endl;
            break;
        }
        else if(sz>0)
        {
            cout<<"服务端收到消息# "<<buffer<<endl;

            string reply="已收到客户端消息> ";
            reply+=buffer;

            send(clientfd,reply.c_str(),reply.size(),0);
            cout<<"已发送回复"<<endl;
            memset(&buffer,0,sizeof(buffer));
       
        }

    }

    close(serverfd);
    close(clientfd);



    return 0;
}